<template>
  <div class="redBook">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="淘宝商品链接">
        <el-input v-model="formInline.spuId" placeholder="商品ID" style="width: 300px;"/>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="getDownload">从淘宝获取链接SPU资源</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="redBooKQueryHandler">刷新列表</el-button>
      </el-form-item>
      <el-form-item label="淘宝Cookie" style="position: relative; left: 200px;">
        <el-input v-model="formInline.cookie" placeholder="淘宝Cookie" style="width: 300px;"/>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="spuId" label="商品Id" width="130"/>
      <el-table-column prop="title" label="商品标题" width="700"/>
      <el-table-column prop="createTime" label="创建时间" width="200"/>
      <el-table-column prop="currentPrice" label="价格" width="100"/>
      <el-table-column prop="extraprice" label="券后" width="100"/>
      <el-table-column prop="salesdesc" label="已销售" width="100"/>
      <el-table-column label="商品图片" width="150" v-slot="scope">
        <el-image
            preview-teleported
            style="width: 100px; height: 100px; cursor: zoom-in"
            :src="scope.row.imageMain"
            :preview-src-list="previewSrcList"
        />
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template #default="scope">
          <!--          <el-button @click="getDownload(scope.row, 0)" type="primary" size="small">全部获取</el-button>-->
          <el-button @click="getDownloadZip(scope.row, 1)" size="small">下载zip到本地</el-button>
          <el-button @click="deletes(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="400">
    </el-pagination>

    <!-- 可选：自定义图片查看器 -->
    <el-image-viewer
        v-if="imageViewerVisible"
        :url-list="imageViewerList"
        @close="imageViewerVisible = false"
    />
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import ElImageViewer, {ElMessage} from 'element-plus'
import 'element-plus/es/components/message/style/css'

import {deleteTbShop, getTbShop, getTbShopList, tbDownloadZip} from '/src/api/newsTop'

const formInline = ref({
  spuId: '',
  cookie: '',
  suffix: ''
})

const page = ref({
  pageNum: 1,
  pageSize: 50,
})

const tableData = ref([])
const previewSrcList = ref([])

// 监听 token 改变自动存储
watch(() => formInline.value.cookie, (newVal) => {
  localStorage.setItem('taoBaoToken', newVal)
})

// 提取 shopId（从商品链接中提取 ID）
watch(() => formInline.value.spuId, (newVal) => {
  // 使用正则表达式匹配
  const idMatch = newVal.match(/[?&]id=(\d+)/); // 匹配 ?id= 后面的数字
  const miIdMatch = newVal.match(/&mi_id=[^&]+/); // 匹配 &mi_id= 后面的值
// 输出结果
  if (idMatch) {
     // 获取 id 值
    formInline.value.spuId = idMatch[1];
  }
  if (miIdMatch) {
     // 获取 &mi_id= 后面的值
    formInline.value.suffix = miIdMatch[0];
  }
})

// 从链接中提取 noteId 和 token
watch(() => formInline.value.noteId, (newVal) => {
  if (!newVal) return
  const {noteId, token} = extractNoteIdAndToken(newVal)
  if (noteId) formInline.value.noteId = noteId
  if (token) formInline.value.redBookToken = token
})

function handleSizeChange(val) {
  console.log(`每页 ${val} 条`);
}


function handleCurrentChange(val) {
  console.log(`当前页: ${val}`);
}


function extractNoteIdAndToken(url) {
  let noteId = ''
  let token = ''
  const noteIdMatch = url.match(/\/item\/([a-zA-Z0-9]+)/)
  if (noteIdMatch) noteId = noteIdMatch[1]
  try {
    const urlObj = new URL(url)
    token = urlObj.searchParams.get('xsec_token') || ''
  } catch (e) {
  }
  return {noteId, token}
}

// 控制图片查看器（可选）
const imageViewerVisible = ref(false)
const imageViewerList = ref([])

const getDownload = () => {
  const param = {
    param: [formInline.value.spuId],
    cookie: formInline.value.cookie,
    suffix: formInline.value.suffix,
  }
  getTbShop(param).then((res) => {
    if (res.data.success) {
      ElMessage.success('获取成功')
      redBooKQueryHandler()
    } else {
      ElMessage.error('获取失败 请检查下cookie 建议换个最新cookie')
    }
  }).catch(() => {
    ElMessage.error('获取失败')
  })
}

const getDownloadZip = (row, type) => {
  tbDownloadZip(row).then((response) => {
    if (response.data == null) {
      ElMessage.error('下载Zip 失败')
      return
    }
    // 创建一个 URL 对象用于下载
    const url = window.URL.createObjectURL(new Blob([response.data]));

    // 创建一个临时的 a 标签来触发下载
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', row.title + ".zip");  // 你可以根据需要设置文件名
    document.body.appendChild(link);
    link.click();  // 触发点击事件下载文件
    document.body.removeChild(link);  // 下载后移除临时 a 标签
    ElMessage.success('下载Zip 成功')
  }).catch(() => {
    ElMessage.error('下载Zip 失败')
  })
}

const redBooKQueryHandler = () => {
  const param = {
    pageNum: page.value.pageNum,
    pageSize: page.value.pageSize,
  }

  getTbShopList(param).then(res => {
    tableData.value = res.data.data
  }).catch(() => {
    ElMessage.error('查询失败')
  })
}

const deletes = (row) => {
  deleteTbShop(row).then(res => {
    ElMessage.success("删除成功")
    redBooKQueryHandler()
  }).catch(() => {
    ElMessage.error('删除失败')
  })
}

onMounted(() => {
  formInline.value.cookie = localStorage.getItem('taoBaoToken') || ''
  redBooKQueryHandler()
})
</script>

<style scoped>
.el-image {
  border: none;
  background-color: #f9f9f9;
  object-fit: cover;
  transition: all 0.3s ease;
  cursor: pointer;
}

.el-image:hover {
  transform: scale(1.02);
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.15);
}
</style>
